package com.st.event.demo.strategy.impl;

import com.st.event.demo.post.OrderFinishTriggerListener;
import com.st.event.demo.source.EventAttribute;
import com.st.event.demo.strategy.AbstractEventStrategy;
import com.st.event.demo.strategy.StrategyHandler;
import com.st.event.demo.strategy.builder.HandlerFactoryBuilder;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

public class EventStrategyManager extends AbstractEventStrategy {

    public EventStrategyManager(HandlerFactoryBuilder factoryBuilder, List<StrategyHandler> strategyHandlers) {
        super(factoryBuilder, strategyHandlers);
    }

    @Override
    public Object doExecute(EventAttribute eventAttribute, Class<?> clientInterface, Method method, Object[] args, Map<String, OrderFinishTriggerListener> params) {
        System.out.println("执行19-----------");
        StrategyHandler handler = getHandler(eventAttribute);
        if (handler == null) {
            return null;
        }
        if (args != null && args.length > 0) {
            for (int i = 0; i < args.length; i++) {
                args[i] = wrap(clientInterface, method, args[i]);
            }
        }
        handler.beforeExecute(eventAttribute, clientInterface, method, args);
        Object result = null;
        try {
            result = handler.execute(eventAttribute, args);
            System.out.println("action result is : " + result);
        } catch (Exception e) {
            handler.exception(eventAttribute, clientInterface, method, args, e);
            System.out.println("action fail!");
        }
        handler.afterExecute(eventAttribute, clientInterface, method, args, params);
        return result;
    }
}
